<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib/jquery.js"></script>
    <script src="./lib/template-web.js"></script>
</head>

<body>
    <button id="btn1">点击获取</button>
    <button id="btn2">点击上传</button>
    <script>
        var btnone = document.querySelector('#btn1')
        var btntwo = document.querySelector('#btn2')
        btnone.onclick = function () {
            itheima({
                method: 'GET',
                url: 'http://www.liulongbin.top:3006/api/getbooks',
                // data: {
                //     id: 1
                // },
                success: res => {
                    console.log(res);
                }
            })
        }
        btntwo.onclick = function () {
            itheima({
                method: 'post',
                url: 'http://www.liulongbin.top:3006/api/addbook',
                data: {
                    bookname: '光文的海王人生',
                    author: '徐大骚',
                    publisher: '67期大舞台'
                },
                success: res => {
                    console.log(res);
                }
            })
        }

        function datan(data) {
            var arr = []
            for (var k in data) {
                var str = k + '=' + data[k];
                arr.push(str)
            }
            return arr.join('&')
        }
        // var theobj = {
        //     method: 'GET',
        //     url: 'http://www.liulongbin.top:3006/api/getbooks',
        //     data: {
        //         name: 'zs',
        //         age: 13,
        //     },
        //     success: res => {
        //         console.log(res);
        //     }
        // }
        // datan(theobj)

        function itheima(options) {
            var xhr = new XMLHttpRequest()
            var qs = datan(options.data)
            if (options.method.toUpperCase() === 'GET') {
                // 发起GET请求
                xhr.open(options.method, options.url + '?' + qs)
                xhr.send()
            } else if (options.method.toUpperCase() === 'POST') {
                // 发起POST请求
                xhr.open(options.method, options.url)
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                xhr.send(qs)
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var result = JSON.parse(xhr.responseText)
                    options.success(result)
                }
            }
        }
        // itheima(theobj)
    </script>
</body>

</html>